<template>
	<view style="width: 100vw;height: 100vh;overflow-y: scroll;background: #fff;">
		<!-- 	<HeaderBar v-if="!isIndex" /> -->
		<image :src="img ? img : ossUrl + `/static/27.png`" mode="widthFix" class="bgcard"></image>
		<view class="titlecard">领取我的名片</view>
		<view class="formcard">
			<!-- v-if="list.length === 0" -->

			<view class="form-listcardbg" v-if="list.length === 0">
				<view class="box_B" style="border-top:1px solid #f3f3f3;">
					<button v-if="!active" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					</button>
					<view class="img">
						<image :src="active?active:'https://cos.dingquan.vip/wx-mini/static/avatar.png'"></image>
					</view>
				</view>
				<view class="form-listcard">
					<view class="form-list-inputcard">
						<input type="text" placeholder="我的姓名" placeholder-class="ac" v-model="form.nickname" />
					</view>
				</view>
			</view>
			<view class="form-listcard" v-if="list.length === 0">
				<view class="form-list-inputcard">
					<button open-type="getPhoneNumber" @getphonenumber="btns">
						{{userInfo.mobile?userInfo.mobile:'获取手机号'}}
					</button>
				</view>
			</view>



			<view class="form-listcard" @click="open">
				<view class="form-list-inputcard">
					<input type="textcard" placeholder="我的领域" placeholder-class="accard" :disabled="true"
						v-model="identity.name" />
				</view>
				<image :src="ossUrl + `/static/28.png`" mode=""></image>
			</view>
			<view class="form-listcard">
				<view class="form-list-inputcard">
					<input type="text" placeholder="我当前的公司" placeholder-class="accard" v-model="form.company" />
				</view>
			</view>
		</view>
		<view class="btnsCard" @click="showlogin">立即领取</view>
		<view class="remark" v-if="description">
			{{description}}
		</view>
		<ElectPopupCard ref="selectRef" v-model="identity" />

		<l-painter :board="template" style="width: 100%;" ref="painterRef" custom-style="position: fixed; left: 200%" />
		<card class="hb-img" style="position: fixed; left: 300%;top:-100%;width: 690rpx;" ref="cardRef" />
		<btnlogin ref="btnlogin" @cancelLogin='cancelLogin' :userInfo='userInfo' @submit="submitLogin" />
		<MemberPopupVue ref="MemberPopupVueRef" @reload="reload" />
	</view>
</template>

<script>
	import ElectPopupCard from './components/selectPopupCard/selectPopupCard.vue'
	import HeaderBar from "@/components/header/header.vue";
	import MemberPopupVue from '@/components/memberPopup/memberPopup.vue'
	import {
		InformationIdentity,
		InformationEditBusinessCard,
		InformationUserBusinessCardHeadData,
		InformationStyleSaving,
		InformationShareStylesSaving,
		InformationBusinessCardList,
		miniLogin,
		InformationUserInfo,
		InformationUserCodeLogin,
		add_circle_business_card,
		circle_recently,
		recently_visited_circle,
		circle_identity
	} from '@/common/http/api.js'
	import btnlogin from '@/components/login/butlogin.vue';
	import {
		uploadImg,
		uploadVideo,
		uploadDel
	} from '@/common/upload.js'
	import {
		ossUpload,
		ossDel
	} from '@/common/oss.js'
	import {
		url
	} from '../../common/config';
	import {
		http
	} from '@/common/util.js'
	export default {
		components: {
			ElectPopupCard,
			HeaderBar,
			MemberPopupVue,
			btnlogin
		},
		data() {
			return {
				active: '',
				visible: true,
				info: [],
				form: {
					nickname: '',
					identity: '',
					company: ''
				},
				identity: {
					name: ''
				},
				template: {},
				cardStyleInfo: '',
				list: [],
				zheshow: true,
				code: '',
				userInfo: {},
				id: '',
				type: 0,
				img: '',
				description: '',
				iscancel: true,
				encryptedData: '',
				iv: ''
			}
		},

		onLoad(e) {
			if (e?.id) {
				this.id = e.id
			}
			if (e.name) {
				this.form.company = e.name
			}
			if (e?.type) {
				this.satae = e.type
			}
			let token = uni.getStorageSync('token')
			if (token) {
				InformationBusinessCardList().then(res => {
					this.list = res.data
				})
				InformationUserInfo().then(res => {
					this.userInfo = res.data
				})

			}

			//获取顶图

			circle_identity({
				id: this.id
			}).then(res => {
				this.img = res.img
				this.description = res.description
			})

		},
		methods: {

			btns(e) {

				if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
					uni.showToast({
						duration: 3000,
						title: '已取消授权',
						icon: 'none'
					})
					return
				}
				this.iv = e.detail.iv
				this.encryptedData = e.detail.encryptedData

				this.submitLogin()
			},

			submitLogin() {
				uni.login({
					provider: 'weixin',
					success: loginRes => {
						this.code = loginRes.code
						let data = {
							code: this.code,
							avatarUrl: this.active,
							iv: this.iv,
							encryptedData: this.encryptedData
						}
						if (this.userId) {
							data['share_userId'] = this.userId
						}
						if (this.shareId) {
							data['login_share_business_card_id'] = this.shareId
						}
						miniLogin(data).then(res => {
							uni.setStorageSync("token", res.data.token)
							InformationUserInfo().then(res => {
								this.userInfo = res.data
							})

						})
					}
				});
			},


			//上传头像
			onChooseAvatar(e) {

				ossUpload(e.detail.avatarUrl).then(res => {
					this.active = res.url
				}).catch(err => {
					uni.showToast({
						duration: 3000,
						title: '上传失败！',
						icon: 'none'
					})
				})
			},
			cancelLogin() {
				this.iscancel = false
			},
			showlogin() {
				if (this.list.length === 0) {
					if (this.form.nickname === '') {
						uni.showToast({
							duration: 3000,
							title: '请输入姓名！',
							icon: 'none'
						})
						return
					}
					if (this.form.nickname.length > 7) {
						uni.showToast({
							duration: 3000,
							title: '姓名不能超过7个字符！',
							icon: 'none'
						})
						return
					}
				}

				if (this.identity.name === '') {
					uni.showToast({
						duration: 3000,
						title: '请选择领域！',
						icon: 'none'
					})
					return
				}
				this.submit()

			},
			toLoading() {


				if (this.type === 1) {

					http({
						h: recently_visited_circle({
							id: this.id
						}),
						title: '申请成功',
						type: 2,
						url: '/pages/index/index'
					})
				} else {
					this.$u.toast('审核中！')
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			},
			openLogin() {
				this.$refs.btnlogin.show()
			},

			open() {
				this.$refs.selectRef.show(this.id)
			},
			submit() {

				if (this.isIndex) {
					let token = uni.getStorageSync('token')
					if (token) {
						this.httpAdd()
					} else {
						//this.$refs.btnlogin.show()
						uni.showLoading()
						InformationUserCodeLogin(data).then(res => {
							// uni.setStorageSync("token",res.data.token)
							// uni.reLaunch({
							// 	url:'/pages/loading/loading'
							// })
							if (res.data?.token) {
								uni.setStorageSync("token", res.data.token)
							}
							this.$store.commit('setIsRefresh', true)
							this.httpAdd()
						}).finally(err => {
							uni.hideLoading()
						})
					}

				} else {
					this.httpAdd()
				}

			},
			httpAdd() {

				let data = {
					identity: this.identity.name,
					company: this.form.company,
					circle: this.id
				}
				if (this.list.length === 0) {
					data['nickname'] = this.form.nickname
					data['avatarUrl']=this.active
				}
				uni.showLoading({
					title: "领取中...",
					mask: true
				})
				
				add_circle_business_card(data).then(res => {
					if (res.msg == '最多加两个圈，升级VIP无限加圈') {
						uni.hideLoading()
						uni.showModal({
							title: "提示",
							content: "最多加两个圈，升级VIP无限加圈",
							cancelText: '再想想',
							confirmText: '升级vip',
							confirmColor: "#23B97F",
							success: (e) => {
								if (e.confirm) {
									this.$refs.MemberPopupVueRef.show()
								}
							}
						})
						return
					}
					this.type = res.data.type
					this.getCardStyle(res.data.b_id)
				})
			},
			getCardStyle(user_id) {
				InformationUserBusinessCardHeadData({

					business_card_id: user_id
				}).then(res => {
					this.cardStyleInfo = res.data
					this.$refs.cardRef.show(this.cardStyleInfo.business_card_layout, this.cardStyleInfo.user, this
						.cardStyleInfo.user.user_img, this.userInfo)
					this.$nextTick(() => {
						this.setCardHttp()
					})
				})
			},
			setCardStyle() {
				this.$nextTick(() => {

				})
			},
			async setCardHttp() {
				uni.showLoading({
					title: "生成名片中..."
				})
				this.$refs.cardRef.submit().then(data => {

					ossUpload(data).then(res => {
						let business_card_img = res.url
						let data = {
							style_id: this.cardStyleInfo.style_id,
							background_id: this.cardStyleInfo.background_id,
							user_img: this.cardStyleInfo.user.user_img,
							business_card_img,
							business_card_id: this.cardStyleInfo.business_card_id
						}

						uni.showLoading({
							title: "生成名片中..."
						})
						InformationStyleSaving(data).then(res => {
							if (!this.cardStyleInfo.intercept) {
								this.template = {
									css: {
										// 根节点若无尺寸，自动获取父级节点
										width: '333rpx',
										height: '266.4rpx'
									},
									views: [
										//底图
										{
											type: 'image',
											src: this.cardStyleInfo.Template_img,
											css: {
												width: '100%',
												height: '100%',
												top: "0",
												right: "0",
												position: "absolute",
												zIndex: '5',
											}
										},
										//名片
										{
											type: 'image',
											src: business_card_img,
											css: {
												width: '333rpx',
												top: "0",
												right: "0",
												position: "absolute",
												zIndex: '4',
											}
										}
									]
								}
								this.$nextTick(() => {
									this.setShareCardHttp()
								})

							} else {
								// uni.showToast({duration:3000,
								// 	title: '保存成功',
								// 	icon: 'none'
								// })

								setTimeout(() => {
									this.$store.commit('setIsRefresh', true)
									this.toLoading()
								}, 1500)

							}


						})
					}).catch(err => {
						// uni.showToast({duration:3000,
						// 	title: '上传失败！',
						// 	icon: 'none'
						// })
						setTimeout(() => {
							this.toLoading()
						}, 1500)
					})
				}).catch(err => {
					console.log('err', err)
					// uni.showToast({duration:3000,
					// 	title: "未能生成，请重新保存!",
					// 	icon: 'none'
					// })
					setTimeout(() => {
						this.toLoading()
					}, 1500)
				})
			},
			async setShareCardHttp() {
				uni.showLoading({
					mask: true,
					title: "名片上传中..."
				})
				this.$refs.painterRef.canvasToTempFilePathSync({
					fileType: "jpg",
					// 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
					pathType: 'url',
					quality: 1,
					success: (res) => {

						// 非H5 保存到相册
						// H5 提示用户长按图另存
						ossUpload(res.tempFilePath).then(res => {
							let business_card_img = res.url
							let data = {
								share_id: this.cardStyleInfo.share_id,
								share_img: business_card_img,
								business_card_id: this.cardStyleInfo.business_card_id,
								intercept: this.cardStyleInfo.intercept,
								share_title: this.cardStyleInfo.share_title,
							}
							uni.showLoading({
								mask: true,
								title: "名片上传中..."
							})
							InformationShareStylesSaving(data).then(res => {
								// uni.showToast({duration:3000,
								// 	title: '保存成功',
								// 	icon: 'none'
								// })
								this.$store.commit('setIsRefresh', true)
								setTimeout(() => {
									this.$store.dispatch('getShare')
									this.toLoading()
								}, 1500)


							})
						}).catch(err => {
							setTimeout(() => {
								this.toLoading()
							}, 1500)
						})
					},
				});
			}
		}
	}
</script>

<style lang="scss">
	image {
		width: 100%;
		height: 100%;
	}

	.bgcard {
		width: 100%;
		height: unset;
	}

	.titlecard {
		padding: 30rpx 0 50rpx;
		width: 100%;
		text-align: center;
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #131313;
	}

	.formcard {
		width: 606rpx;
		margin: 0 auto;

		.form-listcard {
			height: 90rpx;
			background: #F6F7F8;
			border-radius: 20rpx;
			margin-bottom: 24rpx;
			display: flex;
			padding: 0 21rpx;
			align-items: center;
			box-sizing: border-box;

			.form-list-inputcard {
				flex: 1;
				min-width: 0;
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #BBBBBB;

				input {
					width: 100%;
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #000;
				}

				.accard {
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #BBBBBB;
				}

				button {
					font-family: PingFang SC;
					font-weight: 500 !important;
					font-size: 28rpx !important;
					color: #BBBBBB;
					width: 100%;
					height: 100%;
					text-align: left;
					padding-left: 0;
				}

				button::after {
					border: none;
				}
			}

			image {
				width: 28rpx;
				height: 18rpx;
			}
		}


		.form-listcardbg {
			height: 90rpx;

			margin-bottom: 24rpx;
			display: flex;
			align-items: center;
			box-sizing: border-box;
			justify-content: space-between;

			.form-listcard {
				margin-bottom: 0;
				flex: 1;
			}

			.box_B {
				width: 90rpx;
				height: 90rpx;
				display: flex;
				border-radius: 50%;
				overflow: hidden;
				align-items: center;
				position: relative;
				margin-right: 30rpx;

				button {
					width: 90rpx;
					height: 90rpx;
					display: flex;
					border-radius: 50%;
					position: absolute;
					z-index: 1;
					opacity: 0;
				}

				.img {
					width: 90rpx;
					height: 90rpx;
					display: flex;
					align-items: center;
				}
			}
		}
	}

	.btnsCard {
		width: 577rpx;
		height: 86rpx;
		background: #23B97F;
		border-radius: 43rpx;
		margin: 0 auto;
		display: flex;
		justify-content: center;
		align-items: center;
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #FFFFFF;
		margin-top: 70rpx;
		margin-bottom: 30rpx;
	}

	.remark {
		width: 606rpx;
		margin: 0 auto;
		background: #F6F7F8;
		box-sizing: border-box;
		padding: 20rpx;
		font-family: PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #BBBBBB;
		border-radius: 10rpx;
		text-indent: 2rem;
	}
</style>